package com.homestay.utils;

import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

public class FormBeanUtils {

    /**
     * 将表单提交的数据封装到对应的JavaBean对象
     * @param request HttpServletRequest对象
     * @param clazz 目标JavaBean的Class对象
     * @return 封装了表单数据的JavaBean对象
     */
    public static <T> T populate(HttpServletRequest request, Class<T> clazz) {
        try {
            // 创建JavaBean实例
            T bean = clazz.newInstance();

            // 获取表单所有参数
            Map<String, String[]> parameterMap = request.getParameterMap();

            // 使用BeanUtils封装数据
            BeanUtils.populate(bean, parameterMap);
            return bean;
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException("表单数据封装失败", e);
        }
    }
}
